package com.czk.basicqueue.receive;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/2 16:19
 */
public class ConsumerTest {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建练级工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/czk");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        // 创建连接对象
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("hello", false, false, false, null);
        // 消费消息
        // 参数一：队列名称
        // 参数二：开始消息的自动确认机制
        // 消费时的回调接口
        channel.basicConsume("hello", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
            }
        });
    }
}

